package com.zhenquan.doubanread.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.zhenquan.doubanread.common.ResponseCode;
import com.zhenquan.doubanread.common.ServerResponse;
import com.zhenquan.doubanread.dao.WantReadMapper;
import com.zhenquan.doubanread.pojo.WantRead;
import com.zhenquan.doubanread.service.IWantReadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/2/3 0003.
 */
@Service("iWantReadService")
public class WantReadImpl implements IWantReadService {
    @Autowired
    private WantReadMapper wantReadMapper;


    @Override
    public ServerResponse<String> addOrRemove(WantRead wantRead) {
        if (wantRead == null || wantRead.getId() == null || wantRead.getUserId() == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        //1.先查询数据库中有没有这个数据
        //2.如果有这个数据的话，就将其删除掉
        //3.如果没有这个数据则添加
        WantRead wantReadItem = wantReadMapper.selectByIdAndUserId(wantRead.getId(), wantRead.getUserId());
        if (wantReadItem == null) {
            wantReadMapper.insert(wantRead);
            return ServerResponse.createBySuccess("添加想读列表成功");
        } else {
            wantReadMapper.deleteByIdAndUserId(wantRead.getId(), wantRead.getUserId());
            return ServerResponse.createBySuccess("移除想读列表成功");
        }
    }

    /**
     * 分頁查詢
     *
     * @param userId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public ServerResponse<PageInfo> list(Integer userId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<WantRead> wantReads = wantReadMapper.selectWantReadByUserId(userId);
        PageInfo pageInfo = new PageInfo(wantReads);
        pageInfo.setList(wantReads);
        return ServerResponse.createBySuccess(pageInfo);
    }

    /**
     * 不分页返回所有想读的集合
     * @param userId
     * @return
     */
    @Override
    public ServerResponse<List<WantRead>> list(Integer userId) {
        return ServerResponse.createBySuccess(wantReadMapper.selectWantReadByUserId(userId));
    }


}
